package com.starblink.brand.ui

import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.KeyboardUtils
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.base.activity.BaseTVMActivity
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.extension.dp2px
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.room.entity.SkAntEntity
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.sensorsdata.spm.event.TrackEvent
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.basic.route.RoutePage
import com.starblink.basic.style.view.recyclerview.SimpleGapItemDecor
import com.starblink.basic.util.CheckUtil
import com.starblink.brand.adapter.BrandMoreEndCell
import com.starblink.brand.adapter.BrandRightCell
import com.starblink.brand.databinding.ActivityBrandAllSearchBinding
import com.starblink.brand.databinding.CellBrandItemdecorBinding
import com.starblink.brand.model.BrandAllVM

@Route(path = RoutePage.Brand.BRAND_ALL_SEARCH)
class BrandAllSearchActivity : BaseTVMActivity<ActivityBrandAllSearchBinding,BrandAllVM>() {
    lateinit var rvLayoutManager: LinearLayoutManager
    private var searchTerm: String? = null
    private val brandAdapter by lazyOnNone {
        MutableAdapter(viewModel.brandRightList).apply {
            addVhDelegate {
                BrandRightCell(SpmPageDef.BrandAllSearchPage,this@BrandAllSearchActivity,it,1,getSearchTerm = {
                    searchTerm
                }){position ->
                    if(viewModel.hasNext&&position==viewModel.brandRightList.size-1){
                        //自动加载更多
                        viewModel.reqSearchTopBrand(searchTerm?:"", initData = false, ifShowLoading = false)
                    }
                }
            }
            addVhDelegate {
                BrandMoreEndCell(CellBrandItemdecorBinding.inflate(layoutInflater,it,false))
            }
        }
    }

    override fun initViewBinding(): ActivityBrandAllSearchBinding {
        return ActivityBrandAllSearchBinding.inflate(layoutInflater)
    }

    override fun initData() {
        super.initData()
        rvLayoutManager= LinearLayoutManager(this)
        viewBinding.rvRelatedBrand.layoutManager = rvLayoutManager
        viewBinding.rvRelatedBrand.adapter = brandAdapter
        viewBinding.rvRelatedBrand.addItemDecoration(
            SimpleGapItemDecor(
                horGap = 0.dp2px(),
                verGap = 0.dp2px()
            )
        )
    }

    override fun initView() {
        super.initView()
        inputFocus()
        viewBinding.smartRefreshLayout.setEnableRefresh(false)
        viewBinding.smartRefreshLayout.setEnableLoadMore(true)
        viewBinding.smartRefreshLayout.setOnLoadMoreListener {
            //已经有上拉自动加载 这里不再触发接口请求
            viewBinding.smartRefreshLayout.finishLoadMore(500)
        }

        viewBinding.searchInput.apply {
            onSearchActionDone = { brandName ->
                KeyboardUtils.hideSoftInput(this)
                brandName?.let {
                    searchTerm = brandName.toString()
                    if(!CheckUtil.isEmpty(searchTerm)) {
                        viewModel.reqSearchTopBrand(searchTerm?:"", initData = true, ifShowLoading = true)
                        SpmTrackHandler.addSingleTrackData(
                            SkAntEntity(
                                spmCnt = GTrackerAssistUtils.fetchElementValue(
                                    SpmPageDef.BrandAllSearchPage,
                                    SpmElementDef.SearchKeyword,
                                ),
                                params = mutableMapOf("searchTerm" to (searchTerm?:""),"searchType" to "normal")
                            )
                        )
                    }
                }
            }
        }
    }

    override fun initObservable() {
        super.initObservable()
        FlowBus.with<Boolean>(FlowConst.LOGIN_STATUS_CHANGE).register(this) {
            viewModel.reqSearchTopBrand(searchTerm?:"", initData = true, ifShowLoading = true)
        }
        viewModel.topBrandSaleList.observe(this){
            if(searchTerm ==null){
                return@observe
            }

            if (viewModel.pageNo == 1) {
                //首页 滑动顶部
                viewBinding.rvRelatedBrand.scrollToPosition(0)
            }

            val indexTag = viewModel.brandRightList.size
            //获取当前列表数量后再添加数据进行局部刷新
            viewModel.addBrandList()
            val endTag=viewModel.brandRightList.size-indexTag
            if (indexTag == 0) {
                brandAdapter.refreshAll()
            } else {
                brandAdapter.notifyItemRangeInserted(indexTag, endTag)
            }

            if(viewBinding.smartRefreshLayout.isRefreshing){
                viewBinding.smartRefreshLayout.finishRefresh()
            }
            if (viewBinding.smartRefreshLayout.isLoading) {
                viewBinding.smartRefreshLayout.finishLoadMore()
            }

            if(viewModel.brandRightList.isEmpty()&&!viewModel.hasNext) (
                //无数据显示empty
                viewBinding.empty.visibleOrGone(true) {
                    viewBinding.rvRelatedBrand.visibleOrGone(false)
                    viewBinding.tvRelatedTitle.visibleOrGone(false)
                }
            )else{
                viewBinding.empty.visibleOrGone(false)
                viewBinding.rvRelatedBrand.visibleOrGone(true)
                viewBinding.tvRelatedTitle.visibleOrGone(true)
            }
        }
    }

    private fun inputFocus() {
        viewBinding.searchInput.requestFocus()
        KeyboardUtils.showSoftInput()
    }
}